﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DNA.OpenAPI.Ping;

namespace DNA.Mvc.Publishing.Observers
{
    public class SendTrackbackObserver : EventTypebaseObserver<ArticleUpdateEvent>
    {
        private string webTitle = "";

        public override void Process(ArticleUpdateEvent e)
        {
            if ((e.Article != null) && (e.Article.IsPublished) && (!e.Article.IsPrivate) && (e.Article.IsAppoved) && (!string.IsNullOrEmpty(e.Article.SendTrackbackUrls)))
            {
                //webTitle = e.Web.Title;
                SendTrackbackOnBackground(new ArticleWrapper(e.Article));
            }
        }

        private void SendTrackbackOnBackground(ArticleWrapper article)
        {
            //Send trackback on async call
            var tb_trackbacks = article.GetSendTrackbackUrls();

            //foreach (var _trackbackUri in tb_trackbacks)
            //{
            tb_trackbacks.AsParallel().ForAll(url =>
            {
                if (!url.ToString().Equals(article.PermaLink, StringComparison.OrdinalIgnoreCase))
                {
                    var _trackbackmsg = GetTrackbackMessage(article, new Uri(url));
                    sendTrackbackAction.BeginInvoke(_trackbackmsg, null, null);
                }
            });
        }

        private TrackbackMessage GetTrackbackMessage(ArticleWrapper article, Uri uri)
        {
            string excerpt = article.Summary;
            if (string.IsNullOrEmpty(excerpt))
            {
                excerpt = TextUtility.ClearHtml(article.Body);
                if (excerpt.Length > 100)
                {
                    excerpt = excerpt.Substring(0, 100);
                }
            }
            //var blog=srv.
            return new TrackbackMessage()
            {
                BlogTitle = webTitle,
                DestinationUrl = uri,
                Excerpt = excerpt,
                Title = article.Title,
                UrlToNotifyTrackback = new Uri(article.PermaLink)
            };
        }

        private readonly Action<TrackbackMessage> sendTrackbackAction = new Action<TrackbackMessage>(t => { TrackbackSender.Send(t); });
    }
}
